Print a Christmas tree in JavaScript


Posted by Christy on 2023-01-20

Description: Write a function named tree that accepts an number n and print a Christmas tree with the following patterns

tree(1)
*

tree(5)
    *
   ***
  *****
 *******
*********
    *
    *
    *
    *
    *
function tree(n) {
  if (n === 1) return console.log("*");
  // tree
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - i) + "*".repeat(2 * i - 1));
  }

  // trunk
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - 1) + "*");
  }
}

tree(5);









Related Posts

[ALG101] Unit5:經典題目解解看 ( live coding )

[ALG101] Unit5:經典題目解解看 ( live coding )

Web開發學習筆記09 — 陣列操作方法(Array Methods)& 箭頭函式(Array Function)

Web開發學習筆記09 — 陣列操作方法(Array Methods)& 箭頭函式(Array Function)

[FE201]  gulp 幫你管理任務的 library

[FE201] gulp 幫你管理任務的 library


Comments